﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using OpenCalais.API;
using OpenCalais.Domain;

namespace OpenCalais.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            //Test();
            Test2();


        }

        private static void Test2()
        {

            //if (!EventLog.Exists("RDFCruncher"))
            //    EventLog.CreateEventSource("RDFCruncher", "Errors");
            //var log = new EventLog
            //{
            //    Source = "RDFCruncher"
            //};


            var xml = GetXml(@"http://www.fiercemobilecontent.com/story/news-corp-unveil-digital-newspaper-mobile-devices/2010-08-13"); //XElement.Load(@"E:\Devo\OpenCalaisDotNet\OpenCalais\OpenCalais.Console\ParsedDoc.xml");

            XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

            var descriptions = xml.Elements(rdf + "Description");

            var instances = new List<object>();

            foreach (var d in descriptions)
            {
                var resource = d.Element(rdf + "type").Attribute(rdf + "resource").Value;


                var domain = Assembly.Load("OpenCalais");

                var type = (from t in domain.GetTypes()
                            where t.Namespace.Contains("Domain")
                                  && t.IsClass
                                  && t.GetCustomAttributes(typeof (RDFAbout),
                                                           true).Count() == 1
                                  && (t.GetCustomAttributes(typeof (RDFAbout),
                                                            true).First() as RDFAbout).Value.Trim().ToLower() == resource.Trim().ToLower()
                            select t).FirstOrDefault();

                if (type != null)
                {
                    var instance = Activator.CreateInstance(type);
                    if (d.Attributes(rdf + "about").Count() == 1)
                        ((Resource)instance).AboutUri = d.Attribute(rdf + "about").Value;

                    var props = type.GetProperties().Where(p => p.Name != "AboutUri");

                    foreach (var prop in props)
                    {
                        var propUrl = (prop.GetCustomAttributes(typeof (RDFAbout),
                                                                true).FirstOrDefault() as RDFAbout).Value;

                        XNamespace c = "http://s.opencalais.com/1/pred/";
                        var name = propUrl.Split('/').Last();
                        var propElement = d.Element(c + name.ToLower());

                        if (prop.PropertyType == typeof (String)
                            && propElement != null
                            &&
                            !string.IsNullOrEmpty(propElement.Value))
                            prop.SetValue(instance,
                                          propElement.Value,
                                          null);


                        if (prop.PropertyType == typeof (DateTime)
                            && propElement != null
                            &&
                            !string.IsNullOrEmpty(propElement.Value))
                            try
                            {
                                prop.SetValue(instance,
                                              DateTime.Parse(propElement.Value),
                                              null);
                            }
                            catch (Exception ex)
                            {

                                //throw;
                                //log.WriteEntry(ex.ToString());
                            }




                    }

                    instances.Add(instance);
                }
            }

            foreach (var instance in instances)
            {

                var t = instance.GetType();
                var pr = t.GetProperties();
                var objProps = pr.Where(p => p.PropertyType != typeof (String)).ToList();

                foreach (var prop in instance.GetType().GetProperties()
                    .Where(p => p.PropertyType != typeof (String)
                                && p.PropertyType != typeof (DateTime)))
                {

                    var aboutUri = "";


                }
            }
            var orderedInstances = instances.OrderBy(i => i.GetType().Name).ToList();

                //log.WriteEntry("Processed Instance.");

                cumSystem.Console.ReadKey();

            
        }

        private static XElement GetXml(string url) {

            string licenseId = "TODO-ENTER-YOUR-KEY-HERE";
            string content;
            //string url = "http://www.prnewswire.com/news-releases/unicef-appeals-for-473-million-for-disaster-relief-in-pakistan-100114494.html";
            var calais = new calais();

            string paramsXml =  "<c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" +
                                "<c:processingDirectives c:contentType=\"Text/HTML\" c:outputFormat=\"XML/RDF\" c:calculateRelevanceScore=\"True\" c:enableMetadataType=\"GenericRelations\" />" +
                                "<c:userDirectives c:allowDistribution=\"False\" c:allowSearch=\"False\" c:submitter=\"MWS\" /></c:params>";

            using (var wc = new WebClient())
                content = wc.DownloadString(url);


            


            var resp = calais.Enlighten(licenseId,
                             content,
                             paramsXml);


            return XElement.Parse(resp);
        }
    }
}
